package com.dxyxx.framework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.http.Header;
import org.codehaus.jackson.type.JavaType;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import br.com.pierry.simpletoast.SimpleToast;

import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.pojo.User;
import com.dxyxx.pojo.ZimgResult;
import com.dynamic.Bimp;
import com.dynamic.FileUtils;
import com.dynamic.PhotoActivity;
import com.gghl.view.wheelview.ActionSheetDialog;
import com.gghl.view.wheelview.ActionSheetDialog.OnSheetItemClickListener;
import com.gghl.view.wheelview.ActionSheetDialog.SheetItemColor;
import com.gghl.view.wheelview.JudgeDate;
import com.gghl.view.wheelview.MyAlertDialog;
import com.gghl.view.wheelview.ScreenInfo;
import com.gghl.view.wheelview.WheelMain;
import com.http.HttpUtil;
import com.http.ImageHttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ta.utdid2.android.utils.StringUtils;

public class InfoActivity extends BaseActivity {

	private User user;
	private Context context;
	private RelativeLayout birthday_layout;
	private RelativeLayout image_layout;
	private RelativeLayout name_layout;
	private RelativeLayout sex_layout;
	private String time1;
	private TextView birthdayView;
	WheelMain wheelMain;
	private ImageView headerView;
	private TextView sexView;
	private TextView usernameView;
	public String drr;// 准备上传 头像的url 
	private float dp;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_info);
		context = this;
		userPreferences = UserPreferences.getInstance(getApplicationContext());
		user = userPreferences.getCurrentUser();
		initViews();
	}

	private void callNetwork() {
		progressDialog = ProgressDialog.show(context, null, null);
		progressDialog.setContentView(R.layout.dialog_circle);
		String url = "user/modify";
		RequestParams params = new RequestParams();
		try {
			params.add("birthday", birthdayView.getText().toString());
		} catch (Exception e) {
			e.printStackTrace();
			params.add("birthday", dateFormat.format(user.getBirthday()));
		}
		if (drr != null && returnMd5 != null) {
			params.add("image", returnMd5);// 已更新
		} else if (drr != null && returnMd5 == null) {
			SimpleToast.info(context, "图片上传中");
			return;
		} else {
			params.add("image", user.getImage());
		}
		String sexStr = sexView.getText().toString();
		if ("男生".equals(sexStr)) {
			params.add("sex", "1");
		} else if ("女生".equals(sexStr)) {
			params.add("sex", "2");
		} else {
			params.add("sex", "0");
		}
		params.add("username", usernameView.getText().toString());
		HttpUtil.post(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				new String(arg2);
				AgainPlayer againPlayer = new AgainPlayer(context, new com.dxyxx.dialog.AgainPlayer.CallBack() {
					@Override
					public void method() {
						callNetwork();
					}
				});
				againPlayer.call("貌似没网了！");
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				try {
					JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, User.class);
					ResponseResult<User> rr = getObjectMapper().readValue(arg2, javaType);
					if (rr.getCode() == 1) {
						SimpleToast.ok(context, "更新成功");
						// 更新到数据库
						User returnUser = rr.getObject();
						newUser = returnUser;
						userPreferences.updateUser(returnUser);
						// 关闭 activity
						finish();
					} else if (rr.getCode() == -1) {
						Intent intent = new Intent(context, LoginActivity.class);
						intent.putExtra("relogin", true);
						Toast.makeText(context, " 重新获取token", 0).show();
						startActivityForResult(intent, RELOGIN);
					} else {
						SimpleToast.error(context, rr.getInfo());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onFinish() {
				progressDialog.dismiss();
				super.onFinish();
			}

		});
	}

	private void initViews() {
		TextView titleView = (TextView) findViewById(R.id.title);
		titleView.setText("个人信息");
		titleView.setFocusable(true);
		titleView.setFocusableInTouchMode(true);
		titleView.requestFocus();
		titleView.requestFocusFromTouch();
		titleView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
		ImageView sureButton = (ImageView) findViewById(R.id.nextImageButton);
		sureButton.setImageResource(R.drawable.common_accept_switcher);

		//只有这样才能得到最原始的长度高度

		dp = getResources().getDimension(R.dimen.dp);// 10dp
		sureButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 提交代码
				callNetwork();
			}

		});

		ImageView backButton = ((ImageView) findViewById(R.id.backImageButton));
		backButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		// 个人头像
		headerView = (ImageView) findViewById(R.id.personal_header);

		if (!StringUtils.isEmpty(user.getImage())) {
			String imagePrefix = HttpUtil.baseImageURL;
			imageLoader.displayImage(imagePrefix + user.getImage() + "?p=0", headerView, squareOptions, null);
		} else {
			headerView.setImageResource(R.drawable.logo);//直接显示logo
		}

		// 名字
		usernameView = (TextView) findViewById(R.id.name);
		if (!StringUtils.isEmpty(user.getUsername())) {
			usernameView.setText(user.getUsername());
		}

		// 性别
		sexView = (TextView) findViewById(R.id.sex);
		if (!StringUtils.isEmpty(user.getSex())) {
			switch (user.getSex().charAt(0)) {
			case '0':
				sexView.setText("保密");
				break;
			case '1':
				sexView.setText("男生");
				break;
			case '2':
				sexView.setText("女生");
				break;

			default:
				break;
			}
		}

		birthdayView = (TextView) findViewById(R.id.birthday);
		if (user.getBirthday() != null) {
			birthdayView.setText(dateFormat.format(user.getBirthday()));
		}
		sex_layout = (RelativeLayout) findViewById(R.id.sex_layout);
		sex_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				new ActionSheetDialog(context).builder().setCancelable(true).setCanceledOnTouchOutside(true).addSheetItem("男生", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {
						sexView.setText("男生");
					}
				}).addSheetItem("女生", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {
						sexView.setText("女生");
					}
				}).addSheetItem("保密", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {
						sexView.setText("保密");
					}
				}).show();

			}
		});

		name_layout = (RelativeLayout) findViewById(R.id.name_layout);
		name_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				LayoutInflater inflater1 = LayoutInflater.from(context);
				final View namepicker1 = inflater1.inflate(R.layout.namepicker, null);
				final EditText nameEdit = (EditText) namepicker1.findViewById(R.id.username);
				nameEdit.setText(user.getUsername());
				nameEdit.setSelection(user.getUsername().length());

				final MyAlertDialog dialog = new MyAlertDialog(context).builder().setTitle("请输入您的昵称").setView(namepicker1).setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(View v) {
					}
				});

				dialog.setPositiveButton("保存", new OnClickListener() {
					@Override
					public void onClick(View v) {
						usernameView.setText(((TextView) namepicker1.findViewById(R.id.username)).getText().toString());
					}
				});
				dialog.show(true);

			}

		});
		birthday_layout = (RelativeLayout) findViewById(R.id.birthday_layout);
		birthday_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				LayoutInflater inflater1 = LayoutInflater.from(context);
				final View timepickerview1 = inflater1.inflate(R.layout.timepicker, null);
				ScreenInfo screenInfo1 = new ScreenInfo(InfoActivity.this);
				wheelMain = new WheelMain(timepickerview1);
				wheelMain.screenheight = screenInfo1.getHeight();
				time1 = birthdayView.getText().toString();
				Calendar calendar1 = Calendar.getInstance();
				if (JudgeDate.isDate(time1, "yyyy-MM-dd")) {
					try {
						calendar1.setTime(dateFormat.parse(time1));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				int year1 = calendar1.get(Calendar.YEAR);
				int month1 = calendar1.get(Calendar.MONTH);
				int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
				wheelMain.initDateTimePicker(year1, month1, day1);
				final MyAlertDialog dialog = new MyAlertDialog(context).builder().setTitle("生日").setView(timepickerview1).setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(View v) {

					}
				});
				dialog.setPositiveButton("保存", new OnClickListener() {
					@Override
					public void onClick(View v) {
						Toast.makeText(getApplicationContext(), wheelMain.getTime(), 1).show();
						birthdayView.setText(wheelMain.getTime());
					}
				});
				dialog.show();

			}
		});

		image_layout = (RelativeLayout) findViewById(R.id.image_layout);
		image_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				new ActionSheetDialog(context).builder().setCancelable(true).setCanceledOnTouchOutside(true).addSheetItem("拍照", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {
						photo();

					}
				}).addSheetItem("从相册中选取", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {

						Intent i = new Intent(
						// 相册
								Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						startActivityForResult(i, RESULT_LOAD_IMAGE);
					}
				}).show();

			}

		});
	}

	public void photo() {
		try {
			Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			String sdcardState = Environment.getExternalStorageState();
			String sdcardPathDir = android.os.Environment.getExternalStorageDirectory().getPath() + "/tempImage/";

			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// 有sd卡，是否有myImage文件夹
				File fileDir = new File(sdcardPathDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 是否有headImg文件
				file = new File(sdcardPathDir + System.currentTimeMillis() + ".JPEG");
			}
			if (file != null) {
				path = file.getPath();
				photoUri = Uri.fromFile(file);
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

				startActivityForResult(openCameraIntent, TAKE_PICTURE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static final int TAKE_PICTURE = 0;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int CUT_PHOTO_REQUEST_CODE = 2;
	private static final int SELECTIMG_SEARCH = 3;
	private static final int Write = 4;
	private static final int RELOGIN = 5;
	private String path = "";
	private Uri photoUri;
	private File file = null;

	private void startPhotoZoom(Uri uri, boolean cut) {
		try {

			//获取系统时间 然后将裁剪后的图片保存至指定的文件夹
			SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
			String address = sDateFormat.format(new java.util.Date());
			if (!FileUtils.isFileExist("")) {
				FileUtils.createSDDir("");
			}
			drr = FileUtils.SDPATH + address + ".JPEG";
			Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");

			final Intent intent = new Intent("com.android.camera.action.CROP");

			intent.setDataAndType(uri, "image/*");

			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 480);
			intent.putExtra("outputY", 480);
			// 输出路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			// 输出格式
			intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
			// 不启用人脸识别
			intent.putExtra("noFaceDetection", false);
			intent.putExtra("return-data", false);
			startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (resultCode == -1) {// 拍照
				// 大于500kb ，裁剪
				startPhotoZoom(photoUri, true);
			}
			break;
		case RESULT_LOAD_IMAGE:
			if (resultCode == RESULT_OK && null != data) {// 相册返回
				Uri uri = data.getData();
				if (uri != null) {
					// 大于500kb ，裁剪
					startPhotoZoom(uri, true);
				}
			}

			break;
		case CUT_PHOTO_REQUEST_CODE:
			if (resultCode == RESULT_OK && null != data) {// 裁剪返回
				Bitmap bitmap = Bimp.getLoacalBitmap(drr);
				PhotoActivity.bitmap.add(bitmap);
				bitmap = Bimp.createFramedPhoto(480, 480, bitmap, (int) (dp * 1.6f));
				headerView.setImageBitmap(bitmap);
				// 上传图片。 
				postImage();
			}
			break;
		case SELECTIMG_SEARCH:

			break;
		case Write: //写评论

			break;
		case RELOGIN: //重登陆
			Toast.makeText(context, "token 已更新", 0).show();
			callNetwork();
			break;
		}
	}

	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	private String returnMd5;
	private User newUser;

	private void postImage() {
		// 开始旋转等待。 

		try {
			File myFile = new File(drr);
			RequestParams params = new RequestParams();
			params.put("userfile", myFile);
			ImageHttpUtil.rawpost(params, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					try {
						// get image的 width跟height
						File file = new File(drr);
						if (file.exists()) {

							//返回值，进行设置
							ZimgResult zr = getObjectMapper().readValue(arg2, ZimgResult.class);
							if (!zr.getMd5().equals("false")) {
								SimpleToast.ok(context, "图片上传成功");
								returnMd5 = zr.getMd5();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					drr = null; //  图片上传失败。
					SimpleToast.error(context, "图片上传失败");
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void finish() {
		Intent intent = new Intent();
		// 关闭Activity
		intent.putExtra("result", newUser);
		// 设置返回数据
		setResult(ResultCode.Info, intent);
		super.finish();
	}
}
